#!/usr/bin/perl

$hostPrefix = $ARGV[0];
@location = ($ARGV[1], $ARGV[2]);

$maxX = $ARGV[3];
$maxY = $ARGV[4];

$localHostName = $hostPrefix."_".$location[0]."_".$location[1];

print "Launching ".$localHostName." at location ".$location[0].", ".$location[1]."\n";

@seedList = ();

# minus 2, because are starting from a 1-offset and need to convert to 0-offset
for($o = -2; $o < 1; $o++) {
    my $modX = (($location[0] + $o) % $maxX) + 1;
    my $modY = (($location[1] + $o) % $maxY) + 1;
    my $hostName = $hostPrefix."_".$location[0]."_".$modY;
    my $hostId = $location[0] * $maxY + $modY;
    if($o != -1) {
        push(@seedList, $hostName);
    }
    if($o != -1) {
        $hostName = $hostPrefix."_".$modX."_".$location[1];
        $hostId = $location[0] * $maxY + $modY;
        push(@seedList, $hostName);
    }
}

foreach($i = 0; $i < scalar(@seedList); $i++) {
    my($seedName) = $seedList[$i];
    print "Launching $seedName\n";
    $ENV{'CASSANDRA_CONF'}="/usr/share/ariadne/$seedName/conf";
    system("nohup /usr/share/cassandra/bin/cassandra -p /var/run/$seedName.pid");
}